package jgl.vajra.operator.part.home.fragment;

import android.content.Context;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.fastjson.JSONObject;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import jgl.vajra.operator.R;
import jgl.vajra.operator.bean.GrabListBean;
import jgl.vajra.operator.bean.GrabOrdersBean;
import jgl.vajra.operator.bean.ReceiptStatisticsBean;
import jgl.vajra.operator.bean.SpeechInfoBean;
import jgl.vajra.operator.constant.Constant;
import jgl.vajra.operator.databinding.FragmentGrabOrderBinding;
import jgl.vajra.operator.dialogFragment.ShareFriendsDialogFragment;
import jgl.vajra.operator.event.CityChoiceEvent;
import jgl.vajra.operator.event.GrabDetailsEvent;
import jgl.vajra.operator.event.GrabOrderEvent;
import jgl.vajra.operator.event.GrabOrderLoginStateEvent;
import jgl.vajra.operator.event.GrabOrderModifyEvent;
import jgl.vajra.operator.event.OrderDetailsCancelEvent;
import jgl.vajra.operator.event.PushDanmuInfoEvent;
import jgl.vajra.operator.listener.MessageDlialogListener;
import jgl.vajra.operator.manager.AccountManager;
import jgl.vajra.operator.manager.FragmentManager;
import jgl.vajra.operator.manager.IntentManager;
import jgl.vajra.operator.netty.CarInfoBean;
import jgl.vajra.operator.netty.ClientHandler;
import jgl.vajra.operator.netty.GrabOrderBean;
import jgl.vajra.operator.netty.ImConnection;
import jgl.vajra.operator.netty.MessageBody;
import jgl.vajra.operator.netty.MessageOrderBean;
import jgl.vajra.operator.part.home.contract.GrabOrderContract;
import jgl.vajra.operator.part.home.pop.ModifyPricePop;
import jgl.vajra.operator.part.home.viewModel.GrabOrderViewModel;
import jgl.vajra.operator.utils.RandomUtils;
import jgl.vajra.operator.view.bulletChat.DanMuHelper;
import jgl.vajra.operator.view.bulletChat.DanmakuEntity;
import jgl.vajra.operator.widget.databindingadapter.BaseBindingItemPresenter;
import jgl.vajra.operator.widget.databindingadapter.SingleTypeBindingAdapter;
import jgl.vajra.operator.widget.dialogfragment.GrabAuthDialogFragment;
import jgl.vajra.operator.widget.dialogfragment.MessageDialogFragment;
import jgl.vajra.operator.widget.manager.LoadingFragmentManager;
import jgl.vajra.operator.widget.manager.SPManager;
import jgl.vajra.operator.widget.mvvm.factory.CreateViewModel;
import jgl.vajra.operator.widget.mvvm.view.BaseMVVMFragment;
import jgl.vajra.operator.widget.retrofithelper.rxsubscriber.CommonObserver;
import jgl.vajra.operator.widget.retrofithelper.utils.AEACCoder;
import jgl.vajra.operator.widget.utils.LongTimeUtil;
import jgl.vajra.operator.widget.utils.PhoneUtils;
import jgl.vajra.operator.widget.utils.TimeUtils;
import jgl.vajra.operator.widget.utils.ToastUtils;
import jgl.vajra.operator.widget.utils.UIUtils;

@CreateViewModel(GrabOrderViewModel.class)
public class GrabOrderFragment extends BaseMVVMFragment<GrabOrderViewModel, FragmentGrabOrderBinding> implements GrabOrderContract.View, BaseBindingItemPresenter<String> {

    //浮动按钮按下时x坐标
    private float downX;
    //浮动按钮按下时y坐标
    private float downY;
    /**
     * 按下时浮层x坐标
     */
    float downViewX = 0;
    private ShareFriendsDialogFragment shareFriendsDialogFragment;
    private SpeechInfoBean speechInfoBean;
    private SingleTypeBindingAdapter<GrabOrderBean> adapter;

    public List<GrabOrderBean> listBean;
    private MessageOrderBean beanMessage;
    private List<CarInfoBean> carList;
    private ModifyPricePop modifyPricePop;

    private Handler mDanmuAddHandler;
    private boolean continueAdd;
    private List<DanmakuEntity> danmuList = new ArrayList<>();
    private int num = 0;//循环的数量
    private long period = 15;//秒
    private DanMuHelper mDanMuHelper;
    private List<ReceiptStatisticsBean> statisticsBean = new ArrayList<>();
    private GrabAuthDialogFragment grabAuthDialogFragment;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_grab_order;
    }

    @Override
    public void initView() {
        mBinding.setView(this);

        mBinding.tvTip.setEllipsize(TextUtils.TruncateAt.MARQUEE);
        mBinding.tvTip.setSelected(true);
        mBinding.tvTip.setFocusable(true);
        mBinding.tvTip.setFocusableInTouchMode(true);

        mBinding.tvTitle.setText(16, 0, UIUtils.getColor(R.color.color_0f2cbb));//设置属性
        mBinding.tvTitle.setTextStillTime(3000);//设置停留时长间隔
        mBinding.tvTitle.setAnimTime(300);//设置进入和退出的时间间隔
        mBinding.tvTitle.setOnItemClickListener(i -> {
            //添加豪车
            //IntentManager.toCarAddActivity(mActivity);
        });

        listBean = new ArrayList<>();

        /*List<GrabOrderBean> orderListInfo = SPManager.HomeData.getOrderListInfo(mActivity);
        if (orderListInfo.size() != 0 && !TextUtils.isEmpty(orderListInfo.get(0).useCarTime)) {
            String orderTime = LongTimeUtil.stampToLong(orderListInfo.get(0).useCarTime);
            long time = Long.parseLong(orderTime) + 600000;//超过10分钟删除所有订单
            long currentTime = System.currentTimeMillis();
            if (time > currentTime) {
                listBean.addAll(orderListInfo);
            } else {
                SPManager.HomeData.saveOrderListInfo(mActivity, listBean);
            }
        }
*/
        // 不可嵌套滑动
        mBinding.recyclerView.setNestedScrollingEnabled(false);
        // 取消head 的 recycleView的焦点
        mBinding.recyclerView.setFocusableInTouchMode(false);
        //设置布局管理器
        mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter = new SingleTypeBindingAdapter(getContext(), listBean, R.layout.item_grab_order);
        mBinding.recyclerView.setAdapter(adapter);
        adapter.setItemPresenter(this);

        //获取屏幕宽度
        WindowManager wm = (WindowManager) mActivity.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        final int with = outMetrics.widthPixels;
        final int height = outMetrics.heightPixels;

        mBinding.ivShareFriends.setOnTouchListener((v, event) -> {
            //返回false，是点击事件；返回true，不记为点击事件 参考链接  https://blog.csdn.net/u014043113/article/details/74778414
            switch (event.getAction()) {

                case MotionEvent.ACTION_DOWN:
                    //按下
                    downX = event.getX();
                    downY = event.getY();
                    downViewX = mBinding.ivShareFriends.getX();
                    return true;
                case MotionEvent.ACTION_MOVE:
                    //移动
                    //移动的距离
                    float moveX = event.getX() - downX;// event.getX() 移动的X距离
                    float moveY = event.getY() - downY;// event.getY() 移动的Y距离
                    //当前view= X,Y坐标
                    float viewX = mBinding.ivShareFriends.getX();
                    float viewY = mBinding.ivShareFriends.getY();
                    //view的宽高
                    int viewHeigth = mBinding.ivShareFriends.getWidth();
                    int viewWidth = mBinding.ivShareFriends.getHeight();

                    //X当超出屏幕,取最大值
                    if (viewX + moveX + viewWidth > with) {
                        //靠右
                        mBinding.ivShareFriends.setX(with - viewWidth);
                    } else if (viewX + moveX <= 0) {
                        //靠右
                        mBinding.ivShareFriends.setX(0);
                    } else {
                        //正常
                        mBinding.ivShareFriends.setX(viewX + moveX);
                    }
                    //Y当超出屏幕,取最大值
                    if (viewY + moveY + viewHeigth > height) {
                        //靠下
                        mBinding.ivShareFriends.setY(height - viewHeigth);
                    } else if (viewY + moveY <= 0) {
                        //靠上
                        mBinding.ivShareFriends.setY(0);
                    } else {
                        //正常
                        mBinding.ivShareFriends.setY(viewY + moveY);
                    }
                    return true;


                case MotionEvent.ACTION_UP:
                    //松手
                    float upX = mBinding.ivShareFriends.getX();
                    //屏幕中心点
                    float center = with / 2;
                    if (mBinding.ivShareFriends.getX() > center) {
                        //靠右
                        mBinding.ivShareFriends.setX(with - mBinding.ivShareFriends.getWidth());
                    } else {
                        mBinding.ivShareFriends.setX(0);
                    }
                    //按下时与松手时X值一致的话，就干点别的事情
                    if (downViewX == upX) {
                        if (shareFriendsDialogFragment == null)
                            shareFriendsDialogFragment = new ShareFriendsDialogFragment();
                        shareFriendsDialogFragment.setShareData(mActivity);
                        shareFriendsDialogFragment.show(mActivity.getSupportFragmentManager());
                        return false;
                    } else {
                        return true;
                    }
            }

            return false;
        });

        requestNetData();

        ImConnection.getInstance().connect();//连接
        Observable.interval(30, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new CommonObserver() {
            @Override
            public void onNext(Object o) {
                super.onNext(o);
                //是否在线
                Logger.d("是否在线" + ClientHandler.isLogin);
                if (ClientHandler.isLogin) {

                    mBinding.ivState.setImageResource(R.drawable.ic_line_on);
                    mBinding.tvStateText.setText("在线");
                    mBinding.tvReconnect.setVisibility(View.GONE);

                    long currentTime = System.currentTimeMillis();
                    long heartbeatLastTime = SPManager.HomeData.getSocketHeartbeatLastTime() + 200000;
                    if (currentTime > heartbeatLastTime) {
                        ClientHandler.isLogin = false;
                        mBinding.ivState.setImageResource(R.drawable.ic_line_off);
                        mBinding.tvStateText.setText("离线");
                        mBinding.tvReconnect.setVisibility(View.VISIBLE);
                        ImConnection.getInstance().connect();//连接
                    }

                    Logger.d(currentTime + "是否在线啊" + heartbeatLastTime);

                } else {
                    mBinding.ivState.setImageResource(R.drawable.ic_line_off);
                    mBinding.tvStateText.setText("离线");
                    mBinding.tvReconnect.setVisibility(View.VISIBLE);
                    ImConnection.getInstance().connect();//连接
                    Logger.d("连接中");
                }
                mBinding.llState.setVisibility(View.VISIBLE);
            }
        });

        // initDanmu();

        mDanMuHelper = new DanMuHelper(mActivity);
        // 当前房间内的弹幕
        mBinding.danmakuContainerRoom.prepare();
        mDanMuHelper.add(mBinding.danmakuContainerRoom);


        /*Observable.interval(period, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new CommonObserver() {
            @Override
            public void onNext(Object o) {
                super.onNext(o);
                setDanmuLoop();
            }
        });*/

    }

    /**
     * 发送一条房间内的弹幕
     */
    private void addRoomDanmaku(DanmakuEntity danmakuEntity) {
        if (mDanMuHelper != null) {
            mDanMuHelper.addDanMu(danmakuEntity, true);
        }
    }


    public void initDanmu() {

       /* for (int i = 0; i < 3; i++) {
            Danmu danmu = new Danmu();
            danmu.setHeaderUrl("http://tupian.qqjay.com/tou3/2016/0725/cb00091099ffbf09f4861f2bbb5dd993.jpg");
            danmu.setUserName("Mr.chen" + i);
            danmu.setInfo("我是弹幕啊,不要问我为什么不可以那么长!!!");
            danmuList.add(danmu);
        }
        mBinding.danmuView.add(danmuList);

        //下面是模拟每秒添加一个弹幕的过程
        HandlerThread ht = new HandlerThread("send danmu");
        ht.start();
        mDanmuAddHandler = new Handler(ht.getLooper()) {
            @Override
            public void handleMessage(Message msg) {
                mActivity.runOnUiThread(() -> mBinding.danmuView.add(danmuList));
                //继续添加
                if (continueAdd) {
                    sendEmptyMessageDelayed(0, 1000);
                }
            }
        };*/
    }

    public void requestNetData() {
        Map<String, Object> map = new HashMap<>();
        map.put("Authorization", AccountManager.getInstance().getLoginData(UIUtils.getContext()).authorization);
        map.put("udid", PhoneUtils.getUDID());
        //抢单列表
        mViewModel.getGrabListData(map);

        Map<String, Object> mapSpeech = new HashMap<>();
        Logger.d(RandomUtils.getRandom() + "随机数");
        mapSpeech.put("Authorization", AEACCoder.encrypt(RandomUtils.getRandom()));//随机数
        mapSpeech.put("type", Constant.USER_TYPE);
        //头部轮播提示语
        mViewModel.getSpeechInfoData(mapSpeech);

        getReceiptStatisticsData();
    }

    public void getReceiptStatisticsData(){
        //接单统计
        Map<String, Object> mapStatistics = new HashMap<>();
        mapStatistics.put("Authorization", AccountManager.getInstance().getLoginData(UIUtils.getContext()).authorization);
        mViewModel.getReceiptStatisticsData(mapStatistics);
    }

    @Override
    public void initData() {

    }

    @Override
    public void initEvent() {

    }

    //听单设置
    @Override
    public void onListeningSetting() {
        IntentManager.toListeningSettingActivity(mActivity);
    }

    //重新连接
    @Override
    public void onReconnect() {
        if (!ClientHandler.isLogin) {
            //ToastUtils.showShort("重新连接中");
            LoadingFragmentManager.getInstance().showLoadingDialog(null, "连接中");
            ImConnection.getInstance().connect();//连接
        }
    }

    //热力图
    @Override
    public void onHeatChart() {
        IntentManager.toHeatChartActivity(mActivity);
    }

    @Override
    public void onTriangle() {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < statisticsBean.size(); i++) {
            list.add(statisticsBean.get(i).city);
        }
        if (list.size() != 0)
            IntentManager.toCityChoiceActivity(mActivity, list);
    }

    @Override
    public void returnSpeechInfoBean(SpeechInfoBean speechInfoBean) {
        this.speechInfoBean = speechInfoBean;
        mBinding.tvTitle.setTextList(speechInfoBean.news);

        if (speechInfoBean.news != null && speechInfoBean.news.size() != 0)
            mBinding.tvTip.setText(speechInfoBean.news.get(0));
    }

   /* @Override
    public void returnMessageOrderBean(GrabOrderBean orderBean, String content) {
        MessageOrderBean messageOrderBean = JSONObject.parseObject(content, MessageOrderBean.class);

        for (int i = 0; i < carList.size(); i++) {
            GrabOrderBean data = new GrabOrderBean();
            data.orderId = orderBean.orderId;
            data.model = orderBean.model;
            data.modelDescription = orderBean.modelDescription;
            data.workTimeDescription = orderBean.workTimeDescription;
            data.qty = orderBean.qty;
            data.amount = orderBean.amount;
            data.contactPerson = orderBean.contactPerson;
            data.contactPhone = orderBean.contactPhone;
            data.useCarTime = orderBean.useCarTime;
            data.sysDate = orderBean.sysDate;
            data.remark = orderBean.remark;
            data.extraRequireData = orderBean.extraRequireData;
            data.addressData = orderBean.addressData;

            data.logo = carList.get(i).key;
            data.alias = carList.get(i).value;
//            data.driverInvitation = messageOrderBean.driverInvitation;
            data.newAmount = messageOrderBean.amount;

            data.addressDataSize = data.addressData.size();
            String channelText = "";
            if (data.addressDataSize > 2) {
                int channelNum = data.addressDataSize - 2;
                channelText = "途径地点：其中经过" + channelNum + "个途径点";
            }
            data.channelText = channelText;
            listBean.add(data);

        }
        adapter.refresh();
    }*/

    //详情
    @Override
    public void onDetails(int position, GrabOrderBean itemData) {
        if (itemData.delaySecond.equals("-1")) {
            if (grabAuthDialogFragment == null)
                grabAuthDialogFragment = new GrabAuthDialogFragment();
            grabAuthDialogFragment.setMessageDialogListener(new MessageDlialogListener() {
                @Override
                public void onRightClick() {
                    //添加豪车
                    IntentManager.toCarAddActivity(mActivity);
                }

                @Override
                public void onLeftClick() {

                }
            });
            grabAuthDialogFragment.show(mActivity.getSupportFragmentManager());
            return;
        }
        if (itemData.countDownStart == 0) {
            itemData.countDownStart = System.currentTimeMillis();
        }
        IntentManager.toGrabDetailsActivity(mActivity, itemData);
    }

    //手动移除
    @Override
    public void onCancel(int position, GrabOrderBean data) {
        listBean.remove(position);
        adapter.refresh();

        saveOrderList();

        Map<String, Object> map = new HashMap<>();
        map.put("Authorization", AccountManager.getInstance().getLoginData(UIUtils.getContext()).authorization);
        map.put("orderId", data.orderId);
        map.put("logo", data.logo);
        map.put("udid", data.udid);

        mViewModel.removeGrabOrderData(map);
    }

    //我的出价
    @Override
    public void onMyBid(int position, GrabOrderBean itemData) {
        if (itemData.delaySecond.equals("-1")) {
            if (grabAuthDialogFragment == null)
                grabAuthDialogFragment = new GrabAuthDialogFragment();
            grabAuthDialogFragment.setMessageDialogListener(new MessageDlialogListener() {
                @Override
                public void onRightClick() {
                    //添加豪车
                    IntentManager.toCarAddActivity(mActivity);
                }

                @Override
                public void onLeftClick() {

                }
            });
            grabAuthDialogFragment.show(mActivity.getSupportFragmentManager());
            return;
        }

        /*long maxUseCarTime = TimeUtils.parsDataYMDHMSLong(itemData.sysDate) + 60000;
        long currentTime = System.currentTimeMillis();

        if (currentTime < maxUseCarTime) {
            long time = (maxUseCarTime - currentTime) / 1000;
            ToastUtils.showShort(time + "秒后可出价");
            return;
        }*/

        if (itemData.offerNum >= 3) {
            ToastUtils.showShort("限出价3次");
            return;
        }

        modifyPricePop = new ModifyPricePop(mActivity, itemData.newAmount, itemData.orderId, itemData.logo);
        modifyPricePop.setModifyPriceListener(amount -> {
            itemData.myPrice = amount;
            itemData.offerNum = itemData.offerNum + 1;
            adapter.refresh(position);

        });
        modifyPricePop.showPopupWindow(mBinding.getRoot());
    }

    //抢单
    @Override
    public void onGrabOrders(int position, GrabOrderBean data) {

        long maxUseCarTime = TimeUtils.parsDataYMDHMSLong(data.sysDate) + 30000;
        long currentTime = System.currentTimeMillis();

        if (currentTime < maxUseCarTime) {
            long time = (maxUseCarTime - currentTime) / 1000;
            ToastUtils.showShort(time + "秒后才能抢单");
            return;
        }

        Map<String, Object> map = new HashMap<>();
        map.put("orderId", data.orderId);
        map.put("logo", data.logo);
//        map.put("driverInvitation", data.driverInvitation);
        map.put("amount", data.newAmount);
        map.put("udid", data.udid);
        mViewModel.getGrabOrdersData(map);
    }

    @Override
    public void returnGrabOrdersData(GrabOrdersBean data) {
        ToastUtils.showShort(data.reason);
        if (data.isGrabOrders) {
            for (int i = listBean.size() - 1; i >= 0; i--) {
                if (listBean.get(i).orderId.equals(data.orderId) /*|| listBean.get(i).logo.equals(data.logo)*/)
                    listBean.remove(i);
            }
            IntentManager.toOrderDetailsActivity(mActivity, data.orderId);
        } else {
            for (int i = listBean.size() - 1; i >= 0; i--) {
                if (listBean.get(i).orderId.equals(data.orderId) /*&& listBean.get(i).logo.equals(data.logo)*/)
                    listBean.remove(i);
            }
        }
        adapter.refresh();

        saveOrderList();
    }

    @Override
    public void returnGrabListData(List<GrabListBean> grabListBean) {
        for (int i = 0; i < grabListBean.size(); i++) {
            for (int j = 0; j < grabListBean.get(i).carList.size(); j++) {
                GrabOrderBean message = JSONObject.parseObject(grabListBean.get(i).order.content, GrabOrderBean.class);

                GrabOrderBean data = new GrabOrderBean();
                data.orderId = grabListBean.get(i).order.orderId;
                data.model = message.model;
                data.modelDescription = message.modelDescription;
                data.workTimeDescription = message.workTimeDescription;
                data.qty = message.qty;
                data.amount = message.amount;
                data.contactPerson = message.contactPerson;
                data.contactPhone = message.contactPhone;
                data.useCarTime = message.useCarTime;
                data.sysDate = message.sysDate;
                data.remark = message.remark;
                data.extraRequireData = message.extraRequireData;
                data.addressData = message.addressData;
                data.udid = grabListBean.get(i).udid;

                data.distance = grabListBean.get(i).carList.get(j).distance;
                data.logo = grabListBean.get(i).carList.get(j).key;
                data.alias = grabListBean.get(i).carList.get(j).value;
                data.delaySecond = grabListBean.get(i).carList.get(j).delaySecond;
//            data.driverInvitation = messageOrderBean.driverInvitation;
                data.newAmount = String.valueOf(grabListBean.get(i).order.newAmount);

                data.addressDataSize = data.addressData.size();
                String channelText = "";
                if (data.addressDataSize > 2) {
                    int channelNum = data.addressDataSize - 2;
                    channelText = "途径地点：其中经过" + channelNum + "个途径点";
                }
                data.channelText = channelText;

                data.useYear = TextUtils.isEmpty(message.useYear) ? "无" : message.useYear + "年";
                data.operateExperience = TextUtils.isEmpty(message.operateExperience) ? "无" : message.operateExperience + "年";
                data.otherRequirements = TextUtils.isEmpty(message.otherRequirements) ? "无" : message.otherRequirements;
                data.supplyHostel = TextUtils.isEmpty(message.supplyHostel) ? "无" : message.supplyHostel;
                data.supplyFood = TextUtils.isEmpty(message.supplyFood) ? "无" : message.supplyFood;
                data.picture = message.picture;

                listBean.add(data);
            }
        }
        adapter.refresh();

        saveOrderList();
    }

    @Override
    public void returnReceiptStatisticsData(List<ReceiptStatisticsBean> data) {
        if (data != null && data.size() != 0) {
            statisticsBean.clear();
            statisticsBean.addAll(data);

            int cityPosition=0;
            String cityData = SPManager.HomeData.getCityData();
            for (int i = 0; i < data.size(); i++) {
                if (data.get(i).city.equals(cityData)){
                    cityPosition=i;
                }
            }
            mBinding.setData(data.get(cityPosition));
            mBinding.llcBottom.setVisibility(View.VISIBLE);
        } else {
            mBinding.llcBottom.setVisibility(View.GONE);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGrabDetailsEvent(GrabDetailsEvent event) {

        if (event.data.isGrabOrders) {
            for (int i = listBean.size() - 1; i >= 0; i--) {
                if (listBean.get(i).orderId.equals(event.data.orderId) /*|| listBean.get(i).logo.equals(data.logo)*/)
                    listBean.remove(i);
            }
        } else {
            for (int i = listBean.size() - 1; i >= 0; i--) {
                if (listBean.get(i).orderId.equals(event.data.orderId) /*&& listBean.get(i).logo.equals(data.logo)*/)
                    listBean.remove(i);
            }
        }
        adapter.refresh();
    }


    @Override
    public void onItemClick(int position, String itemData) {

    }

    @Override
    public void onResume() {
        super.onResume();
        mBinding.tvTitle.startAutoScroll();

       /* mBinding.danmuView.startPlay(false);//true表示弹幕的垂直方向是固定的,false则随机
        continueAdd = true;
        mDanmuAddHandler.sendEmptyMessageDelayed(0, 6000);*/
    }

    @Override
    public void onPause() {
        super.onPause();
        mBinding.tvTitle.stopAutoScroll();

      /*  continueAdd = false;
        mDanmuAddHandler.removeMessages(0);*/
    }

    @Override
    protected boolean isRegisterEvent() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGrabOrderEvent(GrabOrderEvent event) {
        carList = event.carList;//推送过来的车的列表
        String udid = event.udid;//推送过来的车的手机唯一标识
        GrabOrderBean orderBean = event.order;//订单数据

        for (int i = 0; i < carList.size(); i++) {
            GrabOrderBean data = new GrabOrderBean();
            data.orderId = orderBean.orderId;
            data.model = orderBean.model;
            data.modelDescription = orderBean.modelDescription;
            data.workTimeDescription = orderBean.workTimeDescription;
            data.qty = orderBean.qty;
            data.amount = orderBean.amount;
            data.contactPerson = orderBean.contactPerson;
            data.contactPhone = orderBean.contactPhone;
            data.useCarTime = orderBean.useCarTime;
            data.sysDate = orderBean.sysDate;
            data.remark = orderBean.remark;
            data.extraRequireData = orderBean.extraRequireData;
            data.addressData = orderBean.addressData;
            data.udid = udid;

            data.distance = carList.get(i).distance;
            data.logo = carList.get(i).key;
            data.alias = carList.get(i).value;
            data.delaySecond = carList.get(i).delaySecond;
//            data.driverInvitation = messageOrderBean.driverInvitation;
            data.newAmount = orderBean.amount;

            data.addressDataSize = data.addressData.size();
            String channelText = "";
            if (data.addressDataSize > 2) {
                int channelNum = data.addressDataSize - 2;
                channelText = "途径地点：其中经过" + channelNum + "个途径点";
            }
            data.channelText = channelText;

            data.useYear = TextUtils.isEmpty(orderBean.useYear) ? "无" : orderBean.useYear + "年";
            data.operateExperience = TextUtils.isEmpty(orderBean.operateExperience) ? "无" : orderBean.operateExperience + "年";
            data.otherRequirements = TextUtils.isEmpty(orderBean.otherRequirements) ? "无" : orderBean.otherRequirements;
            data.supplyHostel = TextUtils.isEmpty(orderBean.supplyHostel) ? "无" : orderBean.supplyHostel;
            data.supplyFood = TextUtils.isEmpty(orderBean.supplyFood) ? "无" : orderBean.supplyFood;
            data.picture = orderBean.picture;

            listBean.add(data);

        }
        adapter.refresh();

        saveOrderList();

       /* String content = event.content;
        carList = event.carList;//推送过来的车的列表
        beanMessage = JSONObject.parseObject(content, MessageOrderBean.class);

        Logger.d(beanMessage.orderId + "订单号");

        Map<String, Object> map = new HashMap<>();
        map.put("Authorization", AccountManager.getInstance().getLoginData(UIUtils.getContext()).authorization);//随机数
        map.put("orderId", beanMessage.orderId);
        mViewModel.getMessageOrderData(map,event.content);*/

    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onGrabOrderModifyEvent(GrabOrderModifyEvent event) {
        String content = event.content;
        MessageOrderBean beanMessage = JSONObject.parseObject(content, MessageOrderBean.class);

        for (int i = 0; i < listBean.size(); i++) {
            if (listBean.get(i).orderId.equals(beanMessage.orderId)) {
                listBean.get(i).newAmount = beanMessage.amount;
            }
        }
        adapter.refresh();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onOrderDetailsCancelEvent(OrderDetailsCancelEvent event) {
        MessageBody messageInfo = JSONObject.parseObject(event.content, MessageBody.class);
        for (int i = adapter.getListData().size() - 1; i >= 0; i--) {
            if (String.valueOf(messageInfo.orderId).equals(adapter.getListData().get(i).orderId)) {
                adapter.getListData().remove(i);
            }
        }
        adapter.refresh();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGrabOrderLoginStateEvent(GrabOrderLoginStateEvent event) {
        LoadingFragmentManager.getInstance().dismissLoadingDialog();
        if (event.state) {
            mBinding.ivState.setImageResource(R.drawable.ic_line_on);
            mBinding.tvStateText.setText("在线");
            mBinding.tvReconnect.setVisibility(View.GONE);

        } else {
            mBinding.ivState.setImageResource(R.drawable.ic_line_off);
            mBinding.tvStateText.setText("离线");
            mBinding.tvReconnect.setVisibility(View.VISIBLE);
        }
        mBinding.llState.setVisibility(View.VISIBLE);
    }

    //选中的开放城市
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCityChoiceEvent(CityChoiceEvent event) {
        mBinding.setData(statisticsBean.get(event.position));
    }

    public void setDanmuLoop() {

        if (danmuList.size() != 0) {
            addRoomDanmaku(danmuList.get(num));
            int sizeNum = danmuList.size() - 1;
            Logger.d(num + "====测试数据啊==" + sizeNum);
            if (num == sizeNum) {
                num = 0;
            } else {
                num = num + 1;
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPushDanmuInfoEvent(PushDanmuInfoEvent event) {
        MessageBody messageInfo = JSONObject.parseObject(event.content, MessageBody.class);
        String info="";
        if ("1".equals(messageInfo.tag)) {
            info = "抢单" + messageInfo.workTime + messageInfo.amount + "元";
            getReceiptStatisticsData();
        } else if ("2".equals(messageInfo.tag)) {
            info = "完成订单客户给了" + messageInfo.scoreLevel + "星好评";
            getReceiptStatisticsData();
        } else if ("3".equals(messageInfo.tag)) {
            info = "平台提现" + messageInfo.amount + "元";
        }

        String name = messageInfo.city + messageInfo.nickname;

        DanmakuEntity danmakuEntity = new DanmakuEntity();
        danmakuEntity.setType(DanmakuEntity.DANMAKU_TYPE_USERCHAT);
        danmakuEntity.setName(name);
        danmakuEntity.setInfo(info);
        danmakuEntity.setAvatar(messageInfo.avatar);
        //danmakuEntity.setTime(messageInfo.sysDate);
        danmakuEntity.setMemberShipLevel(messageInfo.memberShipLevel);
        danmakuEntity.setText("");
        // mBinding.danmuView.add(danmu);
        danmuList.add(danmakuEntity);
        addRoomDanmaku(danmakuEntity);
        Logger.d("111111122222" + messageInfo.nickname);
    }

    //保存数据
    public void saveOrderList() {
        SPManager.HomeData.saveOrderListInfo(adapter.getListData());
    }
}
